package com.jacky.webflux.commons;


import org.springframework.data.domain.Pageable;
import org.springframework.data.domain.Sort;

public class Offset implements Pageable {

    int offset;
    int limit;
    boolean pagingApplied;

    int pageNum;
    int pageSize;

    public Offset(int offset, int limit, boolean pagingApplied) {
        this.offset = offset;
        this.limit = limit;
        this.pagingApplied = pagingApplied;
    }

    public Offset(int pageNum, int pageSize) {
        this.pageNum = pageNum;
        this.pageSize = pageSize;
        this.offset = pageNum * pageSize;
        this.limit = pageSize;
    }


    @Override
    public int getPageNumber() {
        return offset / limit;
    }

    @Override
    public int getPageSize() {
        return limit;
    }

    @Override
    public long getOffset() {
        return offset;
    }

    @Override
    public Sort getSort() {
        return Sort.unsorted();
    }

    @Override
    public Pageable next() {
        return !pagingApplied ? Pageable.unpaged() : new Offset(offset + limit, limit, true);
    }

    @Override
    public Pageable previousOrFirst() {
        return !pagingApplied ?
                Pageable.unpaged() : hasPrevious() ?
                new Offset(offset - limit, limit, true) :
                first();
    }

    @Override
    public Pageable first() {
        return !pagingApplied ? Pageable.unpaged() : new Offset(0, limit, true);
    }

    @Override
    public Pageable withPage(int pageNumber) {
        return new Offset(pageNumber, 10, false);
    }

    @Override
    public boolean hasPrevious() {
        return offset >= limit;
    }

    @Override
    public boolean isPaged() {
        return pagingApplied;
    }

    Offset unpaged() {
        return new Offset(0, 0, false);
    }
}
